package cn.yzj.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * javax servlet 工具类
 *
 * @author gzkemays
 * @since 2022/1/14 22:55
 */
public class ServletUtils {
  /**
   * 写入 json 入响应当中
   *
   * @param response httpServlet 响应
   * @param data 写入数据
   */
  public static void writeJson(HttpServletResponse response, Object data) {
    // 这里很重要，否则页面获取不到正常的JSON数据集
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Method", "*");
    // 输出JSON
    PrintWriter out = null;
    try {
      out = response.getWriter();
      out.write(new ObjectMapper().writeValueAsString(data));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (Objects.nonNull(out)) {
        out.flush();
        out.close();
      }
    }
  }
}
